package vincent.com.layouttest.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.support.annotation.Nullable;
import android.util.Log;

import vincent.com.layouttest.DrawerTopOnActionBar;
import vincent.com.layouttest.util.LogUtil;

/**
 * Created by chenzhengwen on 2015/12/8.
 */
public class MessengerService extends Service {
    public static final int MSG_SAY_HELLO = 1;

    public static final String ACTION_GOTO_MAIN_PAGE = "vincent.com.layouttest.action_goto_main_page";

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            if(ACTION_GOTO_MAIN_PAGE.equals(action)){
                LogUtil.i("czw_messenger_service", "后台启动 主页");
                Intent startIntent = new Intent(MessengerService.this, DrawerTopOnActionBar.class);
//                startIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startIntent.putExtra("from", "messenger_server");
                getApplicationContext().startActivity(startIntent);
            }
        }
    };

    private boolean mRegisterReceiver = false;

    @Override
    public void onCreate() {
        super.onCreate();

        if(!mRegisterReceiver){

            mRegisterReceiver = true;
            IntentFilter filter = new IntentFilter();
            filter.addAction(ACTION_GOTO_MAIN_PAGE);
            this.registerReceiver(mReceiver, filter);
        }

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.i(LogUtil.DEBUG_TAG, "onStartCommand service instance is " + MessengerService.this.toString());
        return START_STICKY;
    }

    public class MessengerHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MSG_SAY_HELLO:
                    LogUtil.i(LogUtil.DEBUG_TAG, "handleMessage service instance is " + MessengerService.this.toString());
                    LogUtil.i(LogUtil.DEBUG_TAG, "hello!");
                    break;
            }
        }
    }

    private final Messenger mMessenger = new Messenger(new MessengerHandler());

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mRegisterReceiver){
            unregisterReceiver(mReceiver);
            mRegisterReceiver = false;
        }
    }
}
